<template>
  <div class="login_container">
    <div class="login_box">
      <div class="atactor_box">
        <img
          src="../../assets/logo.png"
          alt=""
        >
      </div>
      <el-form
        label-width="0px"
        class='user-box'
        :rules="loginRules"
        :model="loginform"
        ref="loginFormRef"
      >
        <!-- 用户名 -->
        <el-form-item
          class='username'
          prop="username"
        >
          <el-input
            prefix-icon="iconfont icon-user"
            v-model="loginform.username"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item
          class='password'
          prop="password"
        >
          <el-input
            prefix-icon="iconfont icon-lock_fill"
            v-model="loginform.password"
            :type="passwordFlag?'password':'text'"
          ></el-input>
          <i
            class='iconfont icon-showpassword'
            :class='passwordFlag?"hidden":"show"'
            @click="passwordFlag=!passwordFlag"
          ></i>
        </el-form-item>
        <el-form-item>
          <el-button
            class="frist"
            type="primary"
            @click="login"
          >登录</el-button>
          <el-button
            class="second"
            type="info"
            @click="reset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loginform: {
        username: 'admin',
        password: '123456'
      },
      passwordFlag: true, // 控制密码框显示或隐藏
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 7, message: '长度在 3 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 初始化表单数据
    reset () {
      this.$refs.loginFormRef.resetFields()
    },
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.loginform)
        if (res.meta.status !== 200) return this.$message.error('登录失败！')
        this.$message.success('登录成功')
        // 1. 将登录成功之后的 token，保存到客户端的 sessionStorage 中
        //   1.1 项目中出了登录之外的其他API接口，必须在登录之后才能访问
        //   1.2 token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
        window.sessionStorage.setItem('token', res.data.token)
        // 2. 通过编程式导航跳转到后台主页，路由地址是 /home
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped>
@import url(../../assets/css/login.css);
</style>
